import { Algorithm } from "../types"

// 数据模型定义
interface MPLPNode {
  id: any
  type: string
  attributes: Record<string, any>
}

interface MPLPEdge {
  source: any
  target: any
  type?: string
  weight?: number
  attributes: Record<string, any>
}

interface MPLPGraph {
  nodes: MPLPNode[]
  edges: MPLPEdge[]
}

interface MPLPInputParams {
  nodes: MPLPNode[]
  edges: MPLPEdge[]
  meta_paths: string[][]
  source_type: string
  target_type: string
  top_k: number
}

interface MPLPPrediction {
  source: any
  target: any
  score: number
  meta_path?: string
}

interface MPLPOutputParams {
  predictions: MPLPPrediction[]
  algorithm: string
  parameters: Record<string, any>
  path_counts: Record<string, number>
  execution_time: number
}

// 添加MVHAND接口定义
interface MVHANDGraph {
  nodes: MPLPNode[]
  edges: MPLPEdge[]
}

interface MVHANDInputParams {
  graph: MVHANDGraph
  embedding_dim: number
  hidden_dim: number
  num_views: number
  contamination: number
  alpha: number
  threshold: number
}

// 添加异常解释的接口定义
interface AnomalyExplanation {
  node_type?: string;
  anomaly_score: number;
  feature_anomalies?: Record<string, any>;
}

interface MVHANDResults {
  anomalous_nodes: Record<string, number>;
  anomaly_explanations?: Record<string, AnomalyExplanation>;
  algorithm: string;
  view_weights?: any[];
  temporal_anomalies?: Record<string, any>;
}

interface AlgorithmRequest {
  task_id: string
  task_callback_url?: string
  input_params: {
    mvhand_params: MVHANDInputParams
  }
}

// 元路径链接预测算法实现
export const MultiViewHeterogeneousAnomalyNodeDetection: Algorithm = {
  name: "多视图异构异常节点检测算法(MVHAND)",
  description: "基于多视图学习的异构图异常节点检测算法，用于检测图中的异常节点",
  configOptions: [
    {
      id: "embedding_dim",
      label: "嵌入维度",
      type: "number",
      defaultValue: 64,
      placeholder: "64"
    },
    {
      id: "hidden_dim",
      label: "隐藏层维度",
      type: "number",
      defaultValue: 32,
      placeholder: "32"
    },
    {
      id: "num_views",
      label: "视图数量",
      type: "number",
      defaultValue: 3,
      placeholder: "3"
    },
    {
      id: "contamination",
      label: "污染率",
      type: "number",
      defaultValue: 0.1,
      placeholder: "0.1"
    },
    {
      id: "alpha",
      label: "权重参数",
      type: "number",
      defaultValue: 0.5,
      placeholder: "0.5"
    },
    {
      id: "threshold",
      label: "异常阈值",
      type: "number",
      defaultValue: 0.7,
      placeholder: "0.7"
    },
    {
      id: "inputData",
      label: "输入数据",
      type: "textarea",
      placeholder: `请输入JSON格式的图数据，例如：
{
  "nodes": [
    {
      "id": "n1",
      "type": "用户",
      "attributes": {"age": 25, "activity": 0.8}
    },
    {
      "id": "n2",
      "type": "商品",
      "attributes": {"price": 199, "category": "电子产品"}
    }
  ],
  "edges": [
    {
      "source": "n1",
      "target": "n2",
      "type": "购买",
      "weight": 1.0,
      "attributes": {"timestamp": "2023-01-01"}
    }
  ]
}`
    }
  ],
  execute: async (config) => {
    try {
      // 生成唯一的任务ID
      const taskId = `mvhand_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
      
      // 解析输入数据
      let graphData: MVHANDGraph
      try {
        graphData = JSON.parse(config.inputData)
      } catch (e) {
        throw new Error("输入数据必须是有效的JSON格式")
      }

      // 验证输入数据结构
      if (!graphData.nodes || !Array.isArray(graphData.nodes) || !graphData.edges || !Array.isArray(graphData.edges)) {
        throw new Error("输入数据必须包含nodes和edges数组")
      }

      // 准备请求数据
      const requestData: AlgorithmRequest = {
        task_id: taskId,
        task_callback_url: "",
        input_params: {
          mvhand_params: {
            graph: graphData,
            embedding_dim: Number(config.embedding_dim) || 64,
            hidden_dim: Number(config.hidden_dim) || 32,
            num_views: Number(config.num_views) || 3,
            contamination: Number(config.contamination) || 0.1,
            alpha: Number(config.alpha) || 0.5,
            threshold: Number(config.threshold) || 0.7
          }
        }
      }

      // 创建任务
      const createResponse = await fetch("http://172.16.4.151:1122/api/mvhand/create", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(requestData)
      })

      if (!createResponse.ok) {
        const errorData = await createResponse.json()
        if (createResponse.status === 422) {
          const validationErrors = errorData.detail || []
          const errorMessages = validationErrors.map((err: any) => 
            `${err.loc?.join('.')}: ${err.msg}`
          ).join('\n')
          throw new Error(`数据验证错误:\n${errorMessages}`)
        }
        throw new Error(errorData.detail || "创建任务失败")
      }

      // 执行任务
      const executeResponse = await fetch(`http://172.16.4.151:1122/api/mvhand/execute/${taskId}`, {
        method: "POST"
      })

      if (!executeResponse.ok) {
        const errorData = await executeResponse.json()
        throw new Error(errorData.detail || "执行任务失败")
      }

      // 轮询获取结果
      let result
      let attempts = 0
      const maxAttempts = 60

      while (attempts < maxAttempts) {
        const getResultResponse = await fetch(`http://172.16.4.151:1122/api/mvhand/result/${taskId}`)
        
        if (!getResultResponse.ok) {
          const errorData = await getResultResponse.json()
          throw new Error(errorData.detail || "获取结果失败")
        }

        result = await getResultResponse.json()
        
        // 添加日志以便调试
        console.log(`第${attempts + 1}次尝试获取结果:`, result.task_status)

        if (result.task_status === "COMPLETED") {
          break
        } else if (result.task_status === "FAILED") {
          throw new Error(result.error_message || "任务执行失败")
        }

        await new Promise(resolve => setTimeout(resolve, 1000))
        attempts++
      }

      if (attempts >= maxAttempts) {
        throw new Error("任务执行超时")
      }

      // 处理结果
      if (!result.output_params?.mvhand_results) {
        throw new Error("结果结构不正确，缺少mvhand_results")
      }

      const outputParams = result.output_params.mvhand_results as MVHANDResults;
      
      // 生成结果摘要
      const resultText = `异常节点检测完成：
检测到的异常节点数量: ${Object.keys(outputParams.anomalous_nodes).length}
算法: ${outputParams.algorithm || "MVHAND"}`

      // 生成异常节点表格
      const anomalyNodesText = Object.keys(outputParams.anomalous_nodes).length > 0 
        ? `异常节点列表:
${Object.entries(outputParams.anomalous_nodes).map(([nodeId, score], index) => 
  `${index+1}. 节点ID: ${nodeId} (异常分数: ${(parseFloat(score as any) * 100).toFixed(2)}%)`
).join('\n')}`
        : "未检测到异常节点"

      // 异常解释
      const explanationsText = outputParams.anomaly_explanations && Object.keys(outputParams.anomaly_explanations).length > 0
        ? `异常解释:
${Object.entries(outputParams.anomaly_explanations).map(([nodeId, explanation]) => 
  `- 节点 ${nodeId} (类型: ${explanation.node_type || "未知"}): 
    异常分数: ${(explanation.anomaly_score * 100).toFixed(2)}%
    ${explanation.feature_anomalies ? `特征异常: ${JSON.stringify(explanation.feature_anomalies)}` : ""}`
).join('\n')}`
        : "无异常解释数据"

      return {
        result: `${resultText}\n\n${anomalyNodesText}\n\n${explanationsText}`,
        steps: [],
        executionTime: 0,
        details: {
          anomalousNodes: outputParams.anomalous_nodes,
          anomalyExplanations: outputParams.anomaly_explanations || {},
          viewWeights: outputParams.view_weights || [],
          temporalAnomalies: outputParams.temporal_anomalies || {}
        }
      }
    } catch (e: any) {
      console.error("MVHAND算法执行出错:", e)
      throw e
    }
  }
} 